const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init()

const db = cloud.database()

/**
 * 往数据表里存储用户数据(不存在新建、存在修改)
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  // 获取 WX Context (微信调用上下文)，包括 OPENID、APPID、及 UNIONID（需满足 UNIONID 获取条件）等信息
  const { OPENID } = cloud.getWXContext()
  const { nickName, avatarUrl } = event.userInfo;
  try {
    await db.collection('user').doc(OPENID).set({
      data: {
        nickName,
        avatarUrl
      }
    })
    return {
      code: 0,
      msg: 'success',
      data: {
        openId: OPENID
      }
    }
  } catch (err) {
    return {
      code: 1,
      msg: err,
      data: {
        openId: OPENID
      }
    }
  }
}

